<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

class CustomerApplets
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $token = $request->input('token');
            if (!$token) {
                return response()->json(['message' => 'Token参数必须填写', 'status' => 202]);
            }

            $user_id = $request->input('user_id');
            if (!$user_id) {
                return response()->json(['message' => 'user_id参数必须填写', 'status' => 4001]);
            }

            $store_id = $request->input('store_id');
            if (!$store_id) {
                return response()->json(['message' => 'store_id参数必须填写', 'status' => 4002]);
            }

            $terminal_type = $request->input('terminal_type');
            if (!$terminal_type) {
                return response()->json(['message' => 'terminal_type参数必须填写', 'status' => 4003]);
            }

            JWTAuth::setToken(JWTAuth::getToken());

            $claim = JWTAuth::getPayload();

            if ($claim['sub']['type'] != "customerAppletsUser") {
                return response()->json(['message' => '此账号不是消费者无法登录', 'status' => 202]);
            }

        } catch (JWTException $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
                return response()->json(['message' => 'Token参数无效', 'status' => 2]);
            } else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
                return response()->json(['message' => 'Token 过期', 'status' => -501]);
            } else {
                return response()->json(['message' => '系统出错了', 'status' => -1]);
            }
        }

        return $next($request);

    }
}
